package com.lighting.smssystem.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lighting.smssystem.model.User;
import com.lighting.smssystem.utils.JWTUtils;
import com.lighting.smssystem.utils.ResponseUtil;
import com.lighting.smssystem.utils.ThreadContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@Slf4j
@Order(100)
@WebFilter(filterName = "authfilter", urlPatterns = "/*")
public class AuthFilter implements Filter {
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 不需要鉴权的路由
     */
    public static ArrayList<String> white = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        white.add("/sms/cred/verifyCode");
        white.add("/sms/cred/phone");
        white.add("/sms/cred/register");
        white.add("/sms/cred/registerCode");
        white.add("/sms/cred/login");
        white.add("/sms/cred/loginAdmin");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest servlet = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        resp.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, X-Token");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");

        String token = servlet.getHeader("X-Token");

        log.info("请求地址 is: {}", servlet.getRequestURI());
        log.info("token is: {}", token);

        if (JWTUtils.validateJwt(token)){

            User user = JWTUtils.parseJwt(token);

            if (user == null) {
                response.getWriter().write(
                        objectMapper.writeValueAsString(
                                ResponseUtil.failed(514, "您暂未登录或者登录超时")
                        )
                );

                response.getWriter().flush();
            } else {

                ThreadContext.set(user);

                chain.doFilter(
                        request,response
                );

            }
        }else{
            if (white.contains(servlet.getRequestURI())) {
                log.info("url白名单：", servlet.getRequestURI());
                chain.doFilter(
                        request,response
                );
            } else {
                response.getWriter().write(
                        objectMapper.writeValueAsString(
                                ResponseUtil.failed(508, "非法访问")
                        )
                );

                response.getWriter().flush();
            }
        }

    }
}